package com.handpay.zztong.hp;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HPLog;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Banner;
import com.handpay.zztong.hp.bean.Chart;
import com.handpay.zztong.hp.bean.UserAccount;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.AdGallery;
import com.handpay.zztong.hp.ui.AdGallery.OnAdItemClickListener;
import com.handpay.zztong.hp.ui.AdGalleryHelper;
import com.handpay.zztong.hp.ui.DialogFactory;
import com.handpay.zztong.hp.ui.LineChart;

import java.util.Hashtable;
import java.util.Vector;

import se.krka.kahlua.vm.LuaTable;

public class GfFoundIndex extends ZZTongActivity implements OnAdItemClickListener {
	private AdGallery adGallery;
	private AdGalleryHelper adGalleryHelper;
	private Banner[] bannerArray = null;
	private Chart[] chartArray = null;
	private UserAccount userAccount = null;
	public static int width;
	public static int height;
	private TextView yesterday_income_money,// 昨日收益
			all_money,// 总金额
			recently_million_copies_of_income_money,// 最近万份收益
			recently_week_income_money,// 近一周收益
			recently_month_income_money,// 近一月收益
			recently_all_income_money,// 总收益
			income_and_ransom_results;// 申购或赎回规则

	private Button btn_recently_income, btn_million_copies_of_income,
			btn_buy_now, btn_purchase, btn_ransom;
	private ImageView image_records;
	private LineChart lineChart;
	private LinearLayout ll_income, ll_user_not_buy, ll_user_had_buy;
	private RelativeLayout rl_advertisement, rl_chartDesc,rl_user_had_buy_btn;
	private boolean hadbuy = false; //控制账户是否开户
	private static final int ACTIVITY_APR_REQCODE_TIP = 105;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.setContentView(R.layout.gffound_index);
		super.onCreate(savedInstanceState);
		getData();
		init();
	}
	//取上个页面数据
    private void getData(){
    	if(getIntent() != null){
			  byte data[] = getIntent().getByteArrayExtra("indexData");
			  LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
 	 		  LuaTable bannerTable = (LuaTable) luaTable.rawget("banner");
 	 		  LuaTable chartsTable = (LuaTable) luaTable.rawget("charts");
 	 			if(bannerTable != null){
 	 			   bannerArray = getBannerArray(bannerTable);
 	 			   hadbuy = false;
 	 			}else {
 	 			    LuaTable userActInfoTable = (LuaTable) luaTable.rawget("userActInfo");
 	 			    if(userActInfoTable != null){
 	 				 userAccount = getUserAccount(userActInfoTable);
 	 				 hadbuy = true;
 	 			    }
 	 			}
 	 			if(chartsTable!=null){
 	 		      chartArray = getChartArray(chartsTable);
 	 			}
			  }
    }
	// 初始化控件
	private void init() {
		width = this.getResources().getDisplayMetrics().widthPixels;// 屏幕的宽度
		height = this.getResources().getDisplayMetrics().heightPixels;// 屏幕的高度
//		myActionBar.setTitleText(R.string.guangfa_index_title);// title
//		findViewById(R.id.right_bar).setBackgroundResource(R.drawable.guangfa_help);
		
		rl_advertisement = (RelativeLayout) findViewById(R.id.rl_advertisement);// 轮换广告布局

		ll_income = (LinearLayout) findViewById(R.id.ll_income);// 显示收益的布局
		image_records = (ImageView) findViewById(R.id.image_records);// 右侧解释的图片
		image_records.setPadding(0, 0, 25, 0);
		yesterday_income_money = (TextView) findViewById(R.id.guangfa_yesterday_income_money);// 昨日收益
		all_money = (TextView) findViewById(R.id.guangfa_all_money);// 总金额

		btn_recently_income = (Button) findViewById(R.id.btn_recently_income);// 最近七日年化收益(%)按钮
		btn_million_copies_of_income = (Button) findViewById(R.id.btn_million_copies_of_income);// 万份收益按钮

		rl_chartDesc = (RelativeLayout) findViewById(R.id.rl_chartDesc);// 图标描述
		lineChart = (LineChart) findViewById(R.id.linechart);// 折线图

		ll_user_not_buy = (LinearLayout) findViewById(R.id.ll_user_not_buy);// 用户未购买折线图下面显示的布局
		btn_buy_now = (Button) findViewById(R.id.btn_buy_now);// 立即购买按钮

		ll_user_had_buy = (LinearLayout) findViewById(R.id.ll_user_had_buy);// 用户购买过之后，这些图下面显示的布局
		recently_million_copies_of_income_money = (TextView) findViewById(R.id.recently_million_copies_of_income_money);
		recently_week_income_money = (TextView) findViewById(R.id.recently_week_income_money);
		recently_month_income_money = (TextView) findViewById(R.id.recently_month_income_money);
		recently_all_income_money = (TextView) findViewById(R.id.recently_all_income_money);
		income_and_ransom_results = (TextView) findViewById(R.id.income_and_ransom_results);// 收益及赎回规则文本
//		income_and_ransom_results.setVisibility(View.GONE);
		
		rl_user_had_buy_btn = (RelativeLayout) findViewById(R.id.rl_user_had_buy_btn);
		btn_purchase = (Button) findViewById(R.id.btn_purchase);// 申购按钮
		btn_ransom = (Button) findViewById(R.id.btn_ransom);// 赎回按钮
		showScreen(hadbuy);
	}

	private void showScreen(boolean buy) {
		// 公共部分
		btn_recently_income.setText(chartArray[0].getChartDesc());
//		btn_recently_income.setTextSize(getResources().getDimension(R.dimen.eighteen_sp));
		if(chartArray.length>1){
		   btn_million_copies_of_income.setText(chartArray[1].getChartDesc());
		}
		if (buy) {
			// 有购买记录的界面显示
			rl_advertisement.setVisibility(View.GONE);
			ll_income.setVisibility(View.VISIBLE);
			ll_user_not_buy.setVisibility(View.GONE);
			ll_user_had_buy.setVisibility(View.VISIBLE);
			rl_user_had_buy_btn.setVisibility(View.VISIBLE);
			income_and_ransom_results.setVisibility(View.GONE);
			yesterday_income_money.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(userAccount.getYesterDayReturn()+"")/100));
			all_money.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(userAccount.getNewnet()+"")/100));
			recently_million_copies_of_income_money.setText(userAccount.getTenTousandsIncomeing());//万份收益单位元
			recently_week_income_money.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(userAccount.getLastWeekRetrunAmount()+"")/100));
			recently_month_income_money.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(userAccount.getLastMonthRetrunAmount()+"")/100));
			recently_all_income_money.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(userAccount.getTotalRetrunAmount()+"")/100));
		} else {
			// 没有购买记录的界面显示
			// 广告轮换
			ll_income.setVisibility(View.GONE);
			adGalleryHelper = new AdGalleryHelper(this, bannerArray, 2000, bannerArray.length>1?true:false,width,height);
			rl_advertisement.addView(adGalleryHelper.getLayout());
			adGallery = adGalleryHelper.getAdGallery();
			adGallery.setAdOnItemClickListener(this);// 轮换广告的点击事件绑定
			ll_user_not_buy.setVisibility(View.VISIBLE);
			ll_user_had_buy.setVisibility(View.GONE);
			rl_user_had_buy_btn.setVisibility(View.GONE);
		}
		// 公共部分
		lineChart.setLayoutParams(new LinearLayout.LayoutParams(
				GfFoundIndex.width, GfFoundIndex.height / 3
						- GfFoundIndex.height / 60));
		lineChart
				.initData(chartArray[0].getXdescs(), chartArray[0].getValues());
		income_and_ransom_results.getPaint()
				.setFlags(Paint.UNDERLINE_TEXT_FLAG);
//		findViewById(R.id.left_bar).setOnClickListener(this);
		image_records.setOnClickListener(this);
		btn_recently_income.setOnClickListener(this);
		btn_million_copies_of_income.setOnClickListener(this);
		btn_buy_now.setOnClickListener(this);
		income_and_ransom_results.setOnClickListener(this);
		btn_purchase.setOnClickListener(this);
		btn_ransom.setOnClickListener(this);

	}
	/**
	 * 获取基金申购信息
	 */
	private void getGFPaymentInfo(){
		 Hashtable<String, String> params = new Hashtable<String, String>();
	     params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
	     params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
	     params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
	     this.doPost(this, Do_ZztGFPaymentInfo, params);
	}
	/**
	 * 发送基金赎回信息
	 */
	private void getRedemptionInfo(){
		 Hashtable<String, String> params = new Hashtable<String, String>();
	     params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
	     params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
	     params.put(BaseProtocolKey.PRODUCTCODE, "HLC"); 
	     this.doPost(this, Do_ZztRedemptionInfo, params);
	}

	@Override
	public boolean netResponse(String action, Hashtable<String, Object> resp,
			boolean showAlert, OnClickListener on) {
   	    boolean result = super.netResponse(action, resp, showAlert, on);
   	    HPLog.e("fyang", "super netresponse result"+result);
   	    closeProgressDialog();
		    if(result == true){
			     this.setResult(Activity.RESULT_CANCELED);
			     return true;
		    }
   	 	    if(action.equals(Do_ZztGFPaymentInfo)){
   	 				byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);			
   	 				if(null != data){
   	 					Intent it = new Intent(this,PurchaseFundActivity.class);
   	 	   	 			it.putExtra("data", data);
   	 	   	 			startActivityForResult(it, ACTIVITY_APR_REQCODE_TIP);
   	 				}
   	 		}else if(action.equals(Do_ZztRedemptionInfo)) {
   	 			byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);			
   	 			if(null != data){
   	 				Intent it = new Intent(this,RedeemFundActivity.class);
   	    	 		it.putExtra("data", data);
   	    	 	startActivityForResult(it, ACTIVITY_APR_REQCODE_TIP);
   	 			}
   	 		}else if(action.equals(Do_ZztGFFundIndex)){
   	       	 byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
  			  LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
   	 		  LuaTable bannerTable = (LuaTable) luaTable.rawget("banner");
   	 		  LuaTable chartsTable = (LuaTable) luaTable.rawget("charts");
   	 		  String responseCode = (String) luaTable.rawget("responseCode");
   	 		  String errorMessage = (String) luaTable.rawget("errMessage");
   	 			if(bannerTable != null){
   	 			   bannerArray = getBannerArray(bannerTable);
   	 			   
   	 			   hadbuy = false;
   	 			}else {
   	 			    LuaTable userActInfoTable = (LuaTable) luaTable.rawget("userActInfo");
   	 			    if(userActInfoTable != null){
   	 				 userAccount = getUserAccount(userActInfoTable);
   	 				 hadbuy = true;
   	 			    }
   	 			}
   	 			if(chartsTable!=null){
   	 		      chartArray = getChartArray(chartsTable);
   	 			}
   	 			showScreen(hadbuy);
   	  	 		if(errorMessage != null && responseCode !=null && chartsTable ==null ){
   	  	 			DialogFactory.showAlertDialog(this, getString(R.string.tip),
	                       errorMessage != null?errorMessage:getString(R.string.guangfa_system_error), true);
   	  	 		}
   	       }
		return false;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == ACTIVITY_APR_REQCODE_TIP && resultCode == REQUEST_APPLYPR_CODE_TIP){
			Hashtable<String, String> params  = new Hashtable<String, String>();
    	    params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
    	    params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
    		params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
    		doPost(this, Do_ZztGFFundIndex, params, true);
		}
	}

	/**
	 * 得到广告列表
	 * 
	 * @param table
	 * @return
	 */
	private Banner[] getBannerArray(LuaTable table) {
		try {
			Vector<LuaTable> items = LuaTableUtil.getArray(table);
			bannerArray = new Banner[items.size()];
			for (int i = 0; i < items.size(); i++) {
				LuaTable lt = items.get(i);
				Banner banner = new Banner((String) lt.rawget("contentUrl"),
						(String) lt.rawget("coverUrl"));
				bannerArray[i] = banner;
			}
//			bannerArray = new Banner[3];
//			for (int i = 0; i < 3; i++) {
//				LuaTable lt = items.get(0);
//				Banner banner = new Banner((String) lt.rawget("contentUrl"),
//						(String) lt.rawget("coverUrl"));
//				bannerArray[i] = banner;
//			}
			return bannerArray;
		} catch (Exception e) {
			HPLog.e("fyang", "getBannerList fail");
			showAlertDialog(this, getResources().getString(R.string.deal_fail), "数据解析错误,请稍后重新尝试", false, new DialogInterface.OnClickListener() {
   				@Override
   				public void onClick(DialogInterface dialog, int which) {
   					//直接跳转到账户页面
   				   goToMain();
					dialog.dismiss();
   				}
   			});
			return null;
		}
	}

	/**
	 * 得到图表列表
	 * 
	 * @param table
	 * @return
	 */
	private Chart[] getChartArray(LuaTable table) {
		try {
			Vector<LuaTable> items = LuaTableUtil
					.getArray(table);
			chartArray = new Chart[items.size()];
			for (int i = 0; i < items.size(); i++) {
				LuaTable lt = items.get(i);
				Chart chart = new Chart(
						0,
						0,
						0,
						0,
						getStringArrayFromTable((LuaTable) lt.rawget("xdescs")),
						null, getFloatArrayFromTable((LuaTable) lt
								.rawget("values")), (String) lt
								.rawget("chartId"), (String) lt
								.rawget("chartDesc"));
				chartArray[i] = chart;
			}
			return chartArray;
		} catch (NumberFormatException e) {
			HPLog.e("fyang", "getChartList fail");
			showAlertDialog(this, getResources().getString(R.string.deal_fail), "数据解析错误,请稍后重新尝试", false, new DialogInterface.OnClickListener() {
   				@Override
   				public void onClick(DialogInterface dialog, int which) {
   					//直接跳转到账户页面
   				   goToMain();
					dialog.dismiss();
   				}
   			});
			return null;
		}
	}

	/**
	 * 此处的参数luaTable,是那种没有键名称的,是可以通过索引取得。
	 * 
	 * @param table
	 * @return
	 */
	public String[] getStringArrayFromTable(LuaTable table) {
		try {
			Vector<String> v = (Vector<String>) LuaTableUtil
					.getArrayList(table);
			String[] obj = new String[v.size()];
			for (int i = 0; i < v.size(); i++) {
				obj[i] = v.get(i).toString();
			}
			return obj;
		} catch (Exception e) {
			HPLog.e("fyang", "getArrayFromTable fail");
			return null;
		}
	}

	private float[] getFloatArrayFromTable(LuaTable table) {
		try {
			Vector<Object> v = (Vector<Object>) LuaTableUtil
					.getArrayList(table);
			float[] obj = new float[v.size()];
			for (int i = 0; i < v.size(); i++) {
				obj[i] = Float.parseFloat(v.get(i).toString());
			}
			return obj;
		} catch (Exception e) {
			HPLog.e("fyang", "getFloatArrayFromTable fail");
			return null;
		}
	}

	/**
	 * 得到用户申购成功纪录
	 * 
	 * @param table
	 * @return
	 */
	public static UserAccount getUserAccount(LuaTable table) {
		try {
			UserAccount uAccount = new UserAccount(
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("yesterDayReturn").toString())),
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("newnet").toString())),
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("avaliableRetrun").toString())),
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("todayPaymentRequestAmount").toString())), 
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("todayPaymentSuccAmount").toString())),
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("avaliableCash").toString())),
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("totalRetrunAmount").toString())), 
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("lastWeekRetrunAmount").toString())), 
					Integer.parseInt(CommonUtils.formatMoeny(table.rawget("lastMonthRetrunAmount").toString())),
				    (String)table.rawget("tenTousandsIncomeing"));
			return uAccount;
		} catch (NumberFormatException e) {
			HPLog.e("fyang", "getUserAccount fail");
			return null;
		}
	}

	@Override
	protected boolean isShownTabs() {
		return false;
	}

	@Override
	protected boolean isShownTopBar() {
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		HPLog.e("fyang", "onResume");
	
	}

	@Override
	public void onSwiperPlugOff() {
		super.onSwiperPlugOff();
	}

	@Override
	public void setItemClick(int position) {
		goToWebView(getString(R.string.guangfa_index_title),bannerArray[position].getContentUrl());
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		/*if (id == R.id.left_bar){
			super.goBack();
		}else if(id == R.id.right_bar){
			goToWebView(getString(R.string.guangfa_user_help),getString(R.string.guangfa_webview_help_url));
		}
		else*/ if(id == R.id.image_records) {
            //跳转到交易记录页面
			HPLog.e("fyang", "跳转到交易记录页面");
			Intent intent = new Intent(GfFoundIndex.this,GfFoundTransactionRecords.class);
			startActivity(intent);
		} else if (id == R.id.btn_recently_income) {
			rl_chartDesc.setBackgroundResource(R.drawable.guangfa_taba1);
			HPLog.e("-----------", "chartArray[0].getValues():" + chartArray[0].getValues());
			lineChart.initData(chartArray[0].getXdescs(),
					chartArray[0].getValues());
			lineChart.invalidate();
		} else if (id == R.id.btn_million_copies_of_income) {
			if(chartArray.length>1){
				rl_chartDesc.setBackgroundResource(R.drawable.tguangfa_taba2);
				lineChart.initData(chartArray[1].getXdescs(),
						chartArray[1].getValues());
				lineChart.invalidate();
			}
		} else if (id == R.id.btn_buy_now) {
			// 立刻购买
			getGFPaymentInfo();
		} else if (id == R.id.income_and_ransom_results) {
			// 申购或者赎回的文本链接
			goToWebView(getString(R.string.guangfa_user_help),getString(R.string.guangfa_fund_help_url));
		} else if (id == R.id.btn_purchase) {
			// 申购
			getGFPaymentInfo();
   	 		
		} else if (id == R.id.btn_ransom) {
			// 赎回
   	 		getRedemptionInfo();
		}
	}

	/**
	 * 跳转到账户页面
	 */
     @Override
    protected void goToMain() {
    	super.goToMain();
    	Intent intent = new Intent();
//    	intent.setClass(this, AccountActivity.class);
    	startActivity(intent);
    }
    private void goToWebView(String title,String url){
    	 Intent intent = new Intent(this, ShowHtmlActivity.class);
         intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, title);
         intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, url);
         startActivity(intent);
    }
    @Override
    public ActionBar getActivityActionBar() {
    	ImageView rightBar = new ImageView(this);
		rightBar.setBackgroundResource(R.drawable.guangfa_help);
		rightBar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				goToWebView(getString(R.string.guangfa_user_help),getString(R.string.guangfa_webview_help_url));
			}
		});
		LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		lp.setMargins(0, 0, 15, 0);
    	return new ActionBar(this.getString(R.string.guangfa_index_title),true,rightBar,lp);
    }
}
